package com.weimob.mcloud.wechatwork.customer.mq.handler.externaluser;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.weimob.mcloud.mcloudratelimitercore.common.RatelimiterInfo;
import com.weimob.mcloud.mcloudratelimitercore.common.enums.BizLimitKeyEnum;
import com.weimob.mcloud.mcloudratelimitercore.common.enums.LimitKeyEnum;
import com.weimob.mcloud.mcloudratelimitercore.common.utils.LimitKeyUtils;
import com.weimob.mcloud.wechatwork.common.enums.CommonBizErrorEnum;
import com.weimob.mcloud.wechatwork.common.enums.MainBizDomainEnum;
import com.weimob.mcloud.wechatwork.common.enums.SubBizDomainEnum;
import com.weimob.mcloud.wechatwork.common.utils.BizErrorCodeGenerator;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.base.RateLimit4CustomerDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.response.ExternalContactBO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.response.FollowUserBO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.channel.response.SelfExternalContactGetBO;
import com.weimob.mcloud.wechatwork.core.base.MultiResponse;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.CustomerEmployeeRelation;
import com.weimob.mcloud.wechatwork.core.entity.relation.customer.Customer;
import com.weimob.mcloud.wechatwork.core.entity.relation.employee.Employee;
import com.weimob.mcloud.wechatwork.core.enums.customer.CustomerStatusEnum;
import com.weimob.mcloud.wechatwork.core.enums.customer.ExternalUserAddWayEnum;
import com.weimob.mcloud.wechatwork.core.enums.employee.EmployeeActiveStatusEnum;
import com.weimob.mcloud.wechatwork.core.enums.employee.EmployeeStatusEnum;
import com.weimob.mcloud.wechatwork.core.service.customer.CustomerService;
import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
import com.weimob.mcloud.wechatwork.customer.constant.RedisLockConstant;
import com.weimob.mcloud.wechatwork.customer.convertor.customer.CustomerConvert;
import com.weimob.mcloud.wechatwork.customer.domain.ArtemisBaseInfo;
import com.weimob.mcloud.wechatwork.customer.domain.ArtemisConstant;
import com.weimob.mcloud.wechatwork.customer.domain.ExternalUserChangeInfo;
import com.weimob.mcloud.wechatwork.customer.externalDependencyProxy.usermanagement.EmployeeProxy;
import com.weimob.mcloud.wechatwork.customer.mq.dto.AddExternalUserSecondDTO;
import com.weimob.mcloud.wechatwork.customer.mq.model.ChatGroupFacade;
import com.weimob.mcloud.wechatwork.customer.redis.RedisService;
import com.weimob.mcloud.wechatwork.customer.service.CustomerTagSyncService;
import com.weimob.mcloud.wechatwork.customer.service.common.CustomerCommonService;
import com.weimob.mcloud.wechatwork.customer.service.impl.ArtemisService;
import com.weimob.mcloud.wechatwork.customer.service.user.constant.RedisKeyConstant;
import com.weimob.mcloud.wechatwork.customer.service.user.enums.CustomerLoseTypeEnum;
import com.weimob.mcloud.wechatwork.customer.service.user.enums.YesOrNoEnum;
import com.weimob.mcloud.wechatwork.customer.third.ChannelAdapterServiceProxy;
import com.weimob.mcloud.wechatwork.customer.third.core.CustomerServiceProxy;
import com.weimob.soa.common.response.SoaResponse;
import com.weimob.soa.common.utils.SoaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Create Time: 2021年01月18日 16:11
 *
 * @author maosheng.li
 **/
@Slf4j
@Service
public class HistoryCorpExternalUserSyncHandler implements CorpExternalUserHandler {

    @Autowired
    private CustomerServiceProxy customerServiceProxy;

    @Autowired
    private ArtemisService artemisService;

    @Reference
    private PrivateSphereService privateSphereService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private CustomerCommonService customerCommonService;

    /**
     * 企微助手产品id
     */
    @Value("${aewc.productId:203}")
    private Long aewcProductId;

    /**
     * 企微助手产品id
     */
    @Value("${history.msg.distinct.hours:24}")
    private Long distinctHours;

    @Autowired
    ChannelAdapterServiceProxy channelAdapterServiceProxy;

    @Resource(name = "customerRelationChangeProcessThreadPool")
    ThreadPoolTaskExecutor customerRelationChangeProcessThreadPool;

    @Resource
    ChatGroupFacade chatGroupFacade;

    @Autowired
    private RedisService redisService;

    @Autowired
    private CustomerTagSyncService customerTagSyncService;

    @Autowired
    private EmployeeProxy employeeProxy;

    @Reference
    CustomerService customerService;

    @Resource
    RedisTemplate<String, RatelimiterInfo> redisTemplate;

    @Override
    public SoaResponse<?, ?> handleCorpExternalUser(ExternalUserChangeInfo externalUserChageInfo) {
        //1、判断是否绑定企微产品私域
        String corpId = externalUserChageInfo.getToUserName();
        Long bosId = externalUserChageInfo.getBosId();
        String externalUserId = externalUserChageInfo.getExternalUserID();
        log.info("历史外部联系人数据同步开始处理,消息体:{}", JSON.toJSON(externalUserChageInfo));

        if (StringUtils.isBlank(corpId) || StringUtils.isBlank(externalUserId)) {
            String errorCode = BizErrorCodeGenerator.generate(MainBizDomainEnum.CUSTOMER_MANAGEMENT
                    , SubBizDomainEnum.CUSTOMER_LIST, CommonBizErrorEnum.NULL_ARGUMENT);
            return SoaUtil.error(errorCode, "历史外部联系人数据初始化,入参校验失败", null);
        }

        //这里只有历史数据同步会进来，根据corpId和externalUserId做幂等
        String historyCustomerSyncKey = RedisLockConstant.getHistoryCustomerSyncKey(bosId, corpId, externalUserId);
        boolean dumpFlag = redisService.setNXNew(historyCustomerSyncKey, "", distinctHours, TimeUnit.HOURS);
        if (!dumpFlag) {
            log.info("历史客户数据同步消息重复, corpId:{}, externalUserId:{}", corpId, externalUserId);
            return SoaUtil.ok(null);
        }

        log.info("外部联系人历史同步开始处理, bosId:{},externalUserId:{}", bosId, externalUserId);
        PrivateSphere privateSphereRequest = new PrivateSphere();
        privateSphereRequest.setCorpId(corpId);
        privateSphereRequest.setBosId(bosId);
        privateSphereRequest.setProductId(aewcProductId);
        SoaResponse<PrivateSphere, Void> fetchPrivateSphere = privateSphereService.fetch(privateSphereRequest);
        if (0L != Long.parseLong(fetchPrivateSphere.getReturnCode()) || Objects.isNull(fetchPrivateSphere.getResponseVo())) {
            //1.1、私域不存在，返回（不落非企微产品外部联系人数据）
            log.warn("消费历史外部联系人数据同步消息查询私域信息失败, corpId:{},bosId:{}", corpId, bosId);
            String errorCode = BizErrorCodeGenerator.generate(MainBizDomainEnum.CUSTOMER_MANAGEMENT
                    , SubBizDomainEnum.CUSTOMER_LIST, CommonBizErrorEnum.ABNORMAL_DATA);
            return SoaUtil.error(errorCode, "消费历史外部联系人数据同步消息查询私域信息失败", null);
        }

        PrivateSphere privateSphere = fetchPrivateSphere.getResponseVo();

        //3、查询企微客户详情（需要接入企微限频）
        RateLimit4CustomerDTO<ExternalUserChangeInfo> rateLimitDTO = new RateLimit4CustomerDTO<>();
        rateLimitDTO.setTaskId(externalUserChageInfo.getTaskId());
        rateLimitDTO.setBizLimitKey(BizLimitKeyEnum.HISTORY_ADD_EXTERNAL_CONTACT_NOW.getKey());
        rateLimitDTO.setLimitKey(LimitKeyEnum.SLEF_EXTERNAL_CONTACT_GET.getKey());
        SoaResponse<SelfExternalContactGetBO, Void> selfExternalContactSoaResponse = channelAdapterServiceProxy.getSelfExternalContact(privateSphere, externalUserId, rateLimitDTO);
        String returnCode = selfExternalContactSoaResponse.getReturnCode();
        // 限频
        if (CommonBizErrorEnum.WECHAT_WORK_LIMIT.getCode().equals(returnCode) || CommonBizErrorEnum.WECHAT_WORK_CONVERT_ID_LIMIT.getCode().equals(returnCode)) {
            //删除幂等redis key
            redisService.delete(historyCustomerSyncKey);
            SelfExternalContactGetBO responseVo = selfExternalContactSoaResponse.getResponseVo();
            if (Objects.nonNull(responseVo)) {
                Long taskId = responseVo.getTaskId();
                log.warn("添加外部联系人调用腾讯接口被限频，taskId:{},msg：{}", taskId, selfExternalContactSoaResponse.getReturnMsg());
                //创建一个redis任务记录
                RatelimiterInfo ratelimiterInfo = new RatelimiterInfo(rateLimitDTO.getLimitKey(), JSON.toJSONString(externalUserChageInfo), rateLimitDTO.getBizLimitKey());
                redisTemplate.opsForValue().set(LimitKeyUtils.buildRedisKey(taskId), ratelimiterInfo, 1, TimeUnit.DAYS);
                return SoaUtil.error(returnCode, "添加外部联系人调用腾讯接口被限频，taskId:" + taskId, null);
            }
        }

        if (0L != Long.parseLong(returnCode) || Objects.isNull(selfExternalContactSoaResponse.getResponseVo())) {
            log.warn("历史-添加客户消息, 查询腾讯客户详情信息失败, response:{}", JSON.toJSONString(selfExternalContactSoaResponse));
            //删除幂等redis key
            redisService.delete(historyCustomerSyncKey);
            String errorCode = BizErrorCodeGenerator.generate(MainBizDomainEnum.CUSTOMER_MANAGEMENT
                    , SubBizDomainEnum.CUSTOMER_LIST, CommonBizErrorEnum.ABNORMAL_DATA);
            return SoaUtil.error(errorCode, "历史-添加客户消息, 查询腾讯客户详情信息失败", null);
        }

        try {
            SelfExternalContactGetBO selfExternalContactGetBO = selfExternalContactSoaResponse.getResponseVo();
            ExternalContactBO externalContactBO = selfExternalContactGetBO.getExternalContactBO();
            List<FollowUserBO> followUserList = selfExternalContactGetBO.getFollowUser();
            String phone = customerCommonService.getCustomerPhone(followUserList);
            List<String> userIdList = followUserList.stream().map(FollowUserBO::getUserid).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(userIdList)) {
                log.error("消费历史外部联系人同步未查到员工信息 corpId:{},externalUserId:{}", corpId, externalUserId);
                String errorCode = BizErrorCodeGenerator.generate(MainBizDomainEnum.CUSTOMER_MANAGEMENT
                        , SubBizDomainEnum.CUSTOMER_LIST, CommonBizErrorEnum.ABNORMAL_DATA);
                return SoaUtil.error(errorCode, "消费历史外部联系人同步未查到员工信息 corpId:" + corpId, null);
            }

            MultiResponse<Employee> multiResponse = employeeProxy.getByEmployeeIdOrTxUserIds(privateSphere, null, userIdList);
            if (Objects.isNull(multiResponse) || CollectionUtils.isEmpty(multiResponse.getDataList())) {
                log.error("消费历史外部联系人同步未查到员工信息 corpId:{},userIdList:{}", corpId, userIdList);
                String errorCode = BizErrorCodeGenerator.generate(MainBizDomainEnum.CUSTOMER_MANAGEMENT
                        , SubBizDomainEnum.CUSTOMER_LIST, CommonBizErrorEnum.ABNORMAL_DATA);
                return SoaUtil.error(errorCode, "消费历史外部联系人同步未查到员工信息", null);
            }
            List<Employee> employeeResDTOList = multiResponse.getDataList();
            // 默认无效 员工未授权或不在坐席则无效 落数据
            List<Integer> statusList = Lists.newArrayList(EmployeeStatusEnum.ACTIVATED.getCode(), EmployeeStatusEnum.DISABLED.getCode(),
                    EmployeeStatusEnum.INACTIVE.getCode(), EmployeeStatusEnum.QUITED.getCode());
            CustomerStatusEnum customerStatus = CustomerStatusEnum.UNAUTHORIZED;
            Map<String, Employee> employeeMap = new HashMap<>();
            for (Employee employeeItem : employeeResDTOList) {
                employeeMap.put(employeeItem.getTxUserId(), employeeItem);
                if (employeeItem.getActiveStatus() != null && EmployeeActiveStatusEnum.ACTIVE.getCode() == employeeItem.getActiveStatus().getCode()
                        && statusList.contains(employeeItem.getStatus().getCode())) {
                    customerStatus = CustomerStatusEnum.DEFAULT;
                }
            }

            //5、查询本地企微用户信息（没有需要写入）
            List<Customer> customerResponseList = null;
            try {
                customerResponseList = customerServiceProxy.fetchCustomerByIds(null, externalUserId, privateSphere);
            } catch (Exception e) {
                log.error("历史外部联系人同步，查询客户信息错误，error", e);
            }

            Boolean newUserFlag = false;

            Customer customer = CustomerConvert.toCustomer(privateSphere, externalUserId, phone, externalContactBO);

            if (CollectionUtils.isEmpty(customerResponseList)) {

                //5.1 如果本地不存在，新增外部联系人数据
                customer.setStatus(customerStatus);
                // 首次添加事件，只有全新客户存一下
                Date firstAddTime = customerCommonService.getCustomerFirstAddTime(followUserList);
                customer.setFirstAddTime(firstAddTime);
                SoaResponse<Customer, ?> customerSoaResponse = customerService.createCustomer(customer);
                if (0L != Long.parseLong(customerSoaResponse.getReturnCode())) {
                    log.error("历史客户同步-企微助手本地存储客户基本信息失败, corpId:{},externalUserId:{}", corpId, externalUserId);
                    String errorCode = BizErrorCodeGenerator.generate(MainBizDomainEnum.CUSTOMER_MANAGEMENT
                            , SubBizDomainEnum.CUSTOMER_LIST, CommonBizErrorEnum.ABNORMAL_DATA);
                    return SoaUtil.error(errorCode, "历史客户同步-企微助手本地存储客户基本信息失败", null);
                }
                customer = customerSoaResponse.getResponseVo();
                newUserFlag = true;

            } else {


                //5.2 如果本地数据存在，更新外部联系人最新数据
                Customer localCustomer = customerResponseList.get(0);
                customer.setId(localCustomer.getId());
                if (CustomerStatusEnum.UNAUTHORIZED.getCode().equals(localCustomer.getStatus().getCode())) {
                    customer.setStatus(customerStatus);
                } else {
                    customer.setStatus(localCustomer.getStatus());
                }
                SoaResponse<Customer, ?> customerSoaResponse = customerService.updateCustomer(customer);
                if (0L != Long.parseLong(customerSoaResponse.getReturnCode())) {
                    log.error("更新外部联系人基本信息失败, customerId:{}", localCustomer.getId());
                    String errorCode = BizErrorCodeGenerator.generate(MainBizDomainEnum.CUSTOMER_MANAGEMENT
                            , SubBizDomainEnum.CUSTOMER_LIST, CommonBizErrorEnum.ABNORMAL_DATA);
                    return SoaUtil.error(errorCode, "历史客户同步-更新外部联系人基本信息失败", null);
                }


                customer = customerSoaResponse.getResponseVo();
                String mobiles = localCustomer.getMobiles();
                if (phone != null && !phone.equals(mobiles)) {
                    SoaResponse<Customer, ?> customerDetailSoa = customerService.updateCustomerDeatil(customer);
                    if (0L != Long.parseLong(customerDetailSoa.getReturnCode())) {
                        //这里异常先不阻塞后续流程，先打错误日志
                        log.error("更新外部联系人详情信息失败, request:{}, response:{}", JSON.toJSONString(customer), JSON.toJSONString(customerDetailSoa));
                    }
                }
            }

            //6、查询企微助手本地客户员工关系数据（如果不存在需要写入，存在需要更新）查询该客户所有关联员工是为了给二阶段业务处理使用
            boolean userStateChangeFlag = false;

            List<CustomerEmployeeRelation> relationList = null;
            try {
                relationList = customerServiceProxy.fetchCustomerEmployeeRelation(customer.getId(), null, privateSphere, null, null, null);
            } catch (Exception e) {
                log.error("查询客户员工关系数据失败");
            }

            Map<String, CustomerEmployeeRelation> customerEmployeeRelationMap = new LinkedHashMap<>();
            if (CollectionUtils.isNotEmpty(relationList)) {
                for (CustomerEmployeeRelation employeeRelation : relationList) {
                    customerEmployeeRelationMap.put(employeeRelation.getEmployee().getId(), employeeRelation);
                }
            }


            for (FollowUserBO followUserBO : followUserList) {


                //2、判断员工是否存在
                Employee employee = employeeMap.get(followUserBO.getUserid());
                if (employee == null) {
                    //2.1、员工不存在，需要打日志具体排查
                    log.info("消费外部联系人未查到员工信息:{}", JSON.toJSONString(externalUserChageInfo));
                    continue;
                }


                //4、加锁防并发处理
                RLock lock = redissonClient.getLock(String.format(RedisKeyConstant.ADD_CORP_USER_EXTERNAL_USER_LOCK, bosId,
                        corpId, customer.getId(), employee.getId()));

                try {

                    //4.1、尝试加锁，最多等待0秒，上锁以后3秒自动解锁  针对同一员工和客户并发，重复的直接放过
                    Boolean lockResult = lock.tryLock(0, 3, TimeUnit.SECONDS);
                    if (!lockResult) {
                        log.info("消费外部联系人分布式锁过滤的消息 corpId:{},externalUserId:{},userId:{}", corpId, externalUserId, followUserBO.getUserid());
                        continue;
                    }


                    Date followUserCreateTime = new Date(followUserBO.getCreatetime() * 1000L);
                    CustomerEmployeeRelation customerEmployeeRelationTarget = CustomerConvert.
                            toCustomerEmployeeRelation(corpId, customer.getId(), employee, followUserCreateTime, followUserBO);


                    CustomerEmployeeRelation customerEmployeeRelationResult = customerEmployeeRelationMap.get(employee.getId());
                    if (customerEmployeeRelationResult == null) {
                        //6.1.1 本地不存在该员工客户关系，新增数据
                        customerEmployeeRelationTarget.setFriended(true);
                        customerService.createCustomerEmployeeRelation(customerEmployeeRelationTarget);
                        userStateChangeFlag = true;
                    } else {
                        customerEmployeeRelationTarget.setBizEventAddTime(followUserCreateTime);
                        if (YesOrNoEnum.YES.getCode().equals(externalUserChageInfo.getHistoryCustomerSync())) {
                            //6.1.4 历史同步事件
                            if (CustomerLoseTypeEnum.EMPLOYEE_DEL_CUSTOMER.getCode().equals(customerEmployeeRelationResult.getLoseType())) {
                                //6.1.5 单向删除员工删除客户，需要将流失类型置为初识标识
                                customerEmployeeRelationTarget.setLoseType(CustomerLoseTypeEnum.INIT.getCode());
                                customerEmployeeRelationTarget.setFriended(Boolean.TRUE);
                            }
                        } else {
                            customerEmployeeRelationTarget.setLoseType(CustomerLoseTypeEnum.INIT.getCode());
                            customerEmployeeRelationTarget.setFriended(Boolean.TRUE);
                        }

                        String localState = customerEmployeeRelationResult.getState();
                        Date localAddTime = customerEmployeeRelationResult.getAddTime();
                        String txState = followUserBO.getState();
                        //数据同步状态本地和企微state不一致需要通知裂变活动
                        if (!Objects.equals(localState, txState) && txState != null) {
                            userStateChangeFlag = true;
                        }
                        //数据同步状态本地和企微添加好友时间不一致需要通知裂变活动
                        if (followUserCreateTime.compareTo(localAddTime) != 0) {
                            userStateChangeFlag = true;
                        }

                        //6.1.6 更新员工客户关系数据
                        SoaUtil.unpack(customerService.updateCustomerEmployeeRelation(customerEmployeeRelationTarget));
                    }


                    try {

                        //调用新的客户标签同步方法
                        customerTagSyncService.syncCustomerTag(privateSphere, externalUserId, null, followUserList, employee);

                    } catch (Exception e) {
                        log.error("初始化客户, 添加客户标签失败, corpId:{}, externalUserId:{}, error:",
                                corpId, externalUserId, e);
                    }

                    //6.1.8 发消息进行二阶段的操作(注意消息体不能过大，过滤无效字段数据)
                    AddExternalUserSecondDTO addExternalUserSecondDTO = new AddExternalUserSecondDTO();
                    addExternalUserSecondDTO.setCustomerId(customer.getId());
                    addExternalUserSecondDTO.setBosId(bosId);
                    addExternalUserSecondDTO.setNewUserFlag(newUserFlag);
                    addExternalUserSecondDTO.setRemarkMobiles(followUserBO.getRemarkMobiles());
                    addExternalUserSecondDTO.setCurrentRelation(filterInvalidRelationAtt(customerEmployeeRelationTarget));
                    addExternalUserSecondDTO.setUserStateChangeFlag(userStateChangeFlag);
                    if (MapUtils.isNotEmpty(customerEmployeeRelationMap)) {
                        List<CustomerEmployeeRelation> results = Lists.newArrayList();
                        for (CustomerEmployeeRelation value : customerEmployeeRelationMap.values()) {
                            CustomerEmployeeRelation filterResult = filterInvalidRelationAtt(value);
                            results.add(filterResult);
                        }
                        addExternalUserSecondDTO.setHisRelationList(results);
                    }
                    addExternalUserSecondDTO.setExternalUserChangeInfo(externalUserChageInfo);
                    ArtemisBaseInfo<AddExternalUserSecondDTO> artemisBaseInfo = new ArtemisBaseInfo<>();
                    if (YesOrNoEnum.YES.getCode().equals(externalUserChageInfo.getHistoryCustomerSync())) {
                        //历史消息
                        artemisBaseInfo.setTopic(ArtemisConstant.Topic.HISTORY_CORP_EXTERNALUSER_SECOND_EVENT);
                    } else {
                        //实时消息
                        artemisBaseInfo.setTopic(ArtemisConstant.Topic.CORP_EXTERNALUSER_SECOND_EVENT);
                    }

                    artemisBaseInfo.setEvent(addExternalUserSecondDTO);
                    artemisBaseInfo.setProducer(ArtemisConstant.USER);
                    artemisService.sendToArtemis(artemisBaseInfo, bosId);

                } catch (Exception e) {
                    log.error("处理历史外部联系人数据初始化失败, corpId:{},externalUserId, error:{}", corpId, externalUserId, e);
                } finally {
                    if (lock != null && lock.isLocked() && lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                }
            }

            //5、客户群好友关系维护
            Customer finalCustomer = customer;
            customerRelationChangeProcessThreadPool.execute(() -> {
                chatGroupFacade.execute(privateSphere, finalCustomer.getExternalUserid(), finalCustomer.getId(), false);
            });

        } catch (Exception e) {
            log.error("历史外部联系人同步，HistoryCorpExternalUserSyncHandler.Exception", e);
        }

        return SoaUtil.ok(null);
    }

    /**
     * 客户员工关系转换去除无效数据
     *
     * @param customerEmployeeRelation
     * @return
     */
    private CustomerEmployeeRelation filterInvalidRelationAtt(CustomerEmployeeRelation customerEmployeeRelation) {
        CustomerEmployeeRelation customerEmployeeRelationResult = new CustomerEmployeeRelation();
        Employee employeeInfo = customerEmployeeRelation.getEmployee();
        if (employeeInfo != null) {
            Employee employeeResult = new Employee();
            employeeResult.setId(employeeInfo.getId());
            employeeResult.setName(employeeInfo.getName());
            employeeResult.setTxUserId(employeeInfo.getTxUserId());
            employeeResult.setVidList(employeeInfo.getVidList());
            employeeResult.setHigherVidList(employeeInfo.getHigherVidList());
            employeeResult.setActionLogs(null);
            employeeResult.setCustomers(null);
            employeeResult.setDepartments(null);
            employeeResult.setExtInfo(null);
            employeeResult.setTagDetails(null);
            employeeResult.setGroups(null);
            customerEmployeeRelationResult.setEmployee(employeeResult);
        }
        customerEmployeeRelationResult.setAddTime(customerEmployeeRelation.getAddTime());
        customerEmployeeRelationResult.setState(customerEmployeeRelation.getState());
        customerEmployeeRelationResult.setFriended(customerEmployeeRelation.getFriended());
        ExternalUserAddWayEnum addWayEnum = customerEmployeeRelation.getAddWay();
        if (Objects.isNull(addWayEnum)) {
            customerEmployeeRelationResult.setAddWay(ExternalUserAddWayEnum.UNKNOWN);
        } else {
            customerEmployeeRelationResult.setAddWay(addWayEnum);
        }
        customerEmployeeRelationResult.setSubAddWay(customerEmployeeRelation.getSubAddWay());
        customerEmployeeRelationResult.setStatus(customerEmployeeRelation.getStatus());
        customerEmployeeRelationResult.setExtInfo(null);
        return customerEmployeeRelationResult;
    }


}
